﻿using Framework.AspNetCore.Operlog;
using Framework.Caching.FreeRedis;
using Framework.Core.Enums;
using Framework.Core.Extensions;
using Framework.Core.Helper;
using Microsoft.Extensions.Caching.Distributed;
using my.abp.Application.Contracts.Cache;
using Newtonsoft.Json;
using System;
using Volo.Abp.Application.Services;
using Volo.Abp.Caching;
using Volo.Abp.Users;

namespace my.abp.Services
{
	public class JsonRootDto
	{
		/// <summary>
		/// 
		/// </summary>
		[JsonProperty("statusCode")]
		public int StatusCode { get; set; }

		/// <summary>
		/// 
		/// </summary>
		[JsonProperty("data")]
		public Data Data { get; set; }

		/// <summary>
		/// 
		/// </summary>
		[JsonProperty("succeeded")]
		public bool Succeeded { get; set; }

		/// <summary>
		/// 
		/// </summary>
		[JsonProperty("errors")]
		public string Errors { get; set; }

		/// <summary>
		/// 
		/// </summary>
		[JsonProperty("extras")]
		public string Extras { get; set; }

		/// <summary>
		/// 
		/// </summary>
		[JsonProperty("timestamp")]
		public int Timestamp { get; set; }
	}

	public class Data
	{
		/// <summary>
		/// 
		/// </summary>
		[JsonProperty("token")]
		public string Token { get; set; }
	}

	public class BookService : ApplicationService
	{
		private readonly IDistributedCache<object, long> _cache;
		private readonly IDistributedCache _cache1;
		private readonly IDistributedCache<object, string> _cache2;
		private readonly HttpHelper _httpHelper;
		private readonly IWebHostEnvironment _hostingEnvironment;
		private readonly IWantDistributedCache _wantDistributedCache;
		private ICurrentUser _currentUser { get; set; }
		public BookService(IDistributedCache<object, long> cache, IDistributedCache cache1, IDistributedCache<object, string> cache2,
			ICurrentUser currentUser, HttpHelper httpHelper, IWebHostEnvironment hostingEnvironment, IWantDistributedCache wantDistributedCache)
		{
			_cache = cache;
			_currentUser = currentUser;
			_cache1 = cache1;
			_cache2 = cache2;
			_httpHelper = httpHelper;
			_hostingEnvironment = hostingEnvironment;
			_wantDistributedCache = wantDistributedCache;
		}

		[OperLog("缓存测试", OperEnum.Export)]
		public async Task<BookCacheItem> GetAsync(long bookId)
		{
			//var item = _cache1.GetObject<BookCacheItem>(bookId.ToString());
			//if (item == null)
			//{
			//	_cache1.SetObject(bookId.ToString(), GetBookFromDatabaseAsync(bookId));
			//}



			//string xmlPath = Path.Combine(_hostingEnvironment.ContentRootPath, "Workspaces");
			//if (!Directory.Exists(xmlPath)) Directory.CreateDirectory(xmlPath);
			//xmlPath = xmlPath + @"\" + "1.exe";
			//await _httpHelper.DownloadFileAsync("https://download.visualstudio.microsoft.com/download/pr/a17b907f-8457-45a8-90db-53f2665ee49e/49bccd33593ebceb2847674fe5fd768e/aspnetcore-runtime-8.0.10-win-x64.exe"
			//, xmlPath, async (totalBytesRead, totalBytes) =>
			//{
			//	Console.WriteLine($"下载进度：{totalBytesRead}/{totalBytes}"); // 输出简要进度字符串
			//	await Task.CompletedTask;
			//}, FileMode.CreateNew);

			//var tmpPost = await _httpHelper.HttpPostAsync<JsonRootDto>("http://localhost:19001/api/app/account/login");
			//Dictionary<string, string> headers = new Dictionary<string, string>();
			//headers.Add("authorization", "Bearer " + tmpPost.Data.Token);
			//string tmpGet = await _httpHelper.HttpGetAsync("http://localhost:19001/api/app/hello-world?name=123", "application/json", headers);

			//var tmpPost1 = await _httpHelper.HttpPostAsync("http://cloud.jxnav.com:5000/api/device-historydata/list", "{\r\n  \"buoysNo\": \"01\",\r\n  \"startTime\": \"2025-04-27 15:14:06\"\r\n}");


			var wanBookCacheItem = _wantDistributedCache.Get<BookCacheItem, string>( bookId.ToString(), "_wantDistributedCache");
			if (wanBookCacheItem == null)
			{
				_wantDistributedCache.Set(bookId, await GetBookFromDatabaseAsync(bookId), "_wantDistributedCache");
			}


			if (_cache1.IsContainKey(bookId.ToString()))
			{
				var tmp1 = _cache1.GetObject<int>(bookId.ToString());
				
			}
			else
			{
				Random ran = new Random();
				int n = ran.Next(100);
				_cache1.SetObject(bookId.ToString(), n);
			}

			_cache2.Set("test:1", await GetBookFromDatabaseAsync(bookId));
			_cache2.Set("test:2", await GetBookFromDatabaseAsync(bookId));

			var tmp2 = _cache2.Get("test:*");
			
			var tmp = _cache.Get(bookId);
			BookCacheItem item;
			if (tmp == null)
			{
				item = await GetBookFromDatabaseAsync(bookId);
				_cache.SetAsync(bookId, item);
			}
			else
			{
				item = Framework.Core.Helper.JsonHelper.StrToObj<BookCacheItem>(tmp.ToString());
			}
			return item;
			//return await _cache.GetOrAddAsync(
			//	bookId, //Guid类型作为缓存键
			//	async () => await GetBookFromDatabaseAsync(bookId),
			//	() => new DistributedCacheEntryOptions
			//	{
			//		AbsoluteExpiration = DateTimeOffset.Now.AddHours(1)
			//	}
			//);
		}
		private async Task<BookCacheItem> GetBookFromDatabaseAsync(long bookId)
		{
			Random ran = new Random();
			int n = ran.Next(100);
			//TODO: 缓存失效，重新获取数据
			return new BookCacheItem { Name = "123", Price = n/10 };
		}
	}
}
